package com;

import java.util.HashMap;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

public class HystrixCacheDemo extends HystrixCommand<String> {

	//用户id
	Integer id;
	 //用一个HashMap来模拟从数据库里拿到的数据
	private HashMap<Integer,String> userList = new HashMap<Integer,String>();
	
	public HystrixCacheDemo(Integer id) {
		// 指定命令组的名字
		super(HystrixCommandGroupKey.Factory.asKey("RequestCacheCommand"));		
		this.id = id;
		userList.put(1, "Tom");
	}


	protected String run() {
		System.out.println("In run");
		return userList.get(id);
	}

	protected String getCacheKey() {
		return String.valueOf(id);
	}
	
	public static void main(String[] args) {
		
		HystrixRequestContext context = HystrixRequestContext.initializeContext();
		
		HystrixCacheDemo cacheDemo1 = new HystrixCacheDemo(1);
		HystrixCacheDemo cacheDemo2 = new HystrixCacheDemo(1);
			
		System.out.println("the result for cacheDemo1 is:" + cacheDemo1.execute());
		System.out.println("whether get from cache：" + cacheDemo1.isResponseFromCache);
			
		System.out.println("the result for cacheDemo2 is:" + cacheDemo2.execute());
		System.out.println("whether get from cache：" + cacheDemo2.isResponseFromCache);
		
		context.shutdown();
		
		context = HystrixRequestContext.initializeContext();
		HystrixCacheDemo cacheDemo3 = new HystrixCacheDemo(1);
		System.out.println("the result for 3 is:" + cacheDemo3.execute());
		System.out.println("whether get from cache：" + cacheDemo3.isResponseFromCache);
		context.shutdown();
	}
}
